package com.hdoit.kylin.web.proposal.providers;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.PageContext;

import org.springframework.util.StringUtils;

import com.hdoit.kylin.logical.user.model.Teacher;
import com.hdoit.kylin.logical.user.service.ITeacherService;
import com.tennetcn.common.aop.CommonApplicationContextUtil;
import com.tennetcn.common.message.ListItem;
import com.tennetcn.common.message.LoginModel;
import com.tennetcn.common.utils.CookieUtils;
import com.tennetcn.component.attribute.provider.ISingleOptionListProvider;
import com.tennetcn.component.web.SessionWebFactory;
import com.tennetcn.plugins.devshorts.enumerable.Enumerable;

public class TutorProvider implements ISingleOptionListProvider<ListItem>{

	private ITeacherService teacherService;
	private List<ListItem> dataList;
	
	public ITeacherService getTeacherService() {
		return teacherService;
	}

	@Resource
	public void setTeacherService(ITeacherService teacherService) {
		this.teacherService = teacherService;
	}

	@Override
	public List<ListItem> getDataList(Object viewData) {
		List<Teacher> teachers= getAllTeachers();
		if(teachers==null||teachers.size()<=0){
			return null;
		}
		dataList=new ArrayList<ListItem>();
		ListItem listItem=null;
		for (Teacher teacher : teachers) {
			listItem=new ListItem();
			listItem.setText(teacher.getTeacherName());
			listItem.setValue(teacher.getTeacherId());
			
			dataList.add(listItem);
		}
		return dataList;
	}

	private List<Teacher> getAllTeachers() {
		SessionWebFactory sessionWebFactory=CommonApplicationContextUtil.getCurrentContext().getBean(SessionWebFactory.class);
		ITeacherService teacherService=CommonApplicationContextUtil.getCurrentContext().getBean(ITeacherService.class);
		LoginModel loginModel=sessionWebFactory.getCurrentLogin();
		
		String loginId=loginModel.getLoginId();
		
		return teacherService.queryListByGroupId(loginId);
	}

	@Override
	public ListItem getSelectedItem(Object value, Object viewData) {
		if(StringUtils.isEmpty(value)){
			try{
				PageContext pageContext=(PageContext)viewData;
				HttpServletRequest httpRequest=(HttpServletRequest)pageContext.getRequest();
				String teacherId=CookieUtils.getCookieValue(httpRequest, "teacherId", true);
				value=teacherId;
			}catch(Exception e){
				return null;
			}
		}
		if(dataList==null){
			return null;
		}
		final String teacherId=value.toString();
		return Enumerable.init(dataList).filter(d->teacherId.equals(d.getValue())).first();
	}

}
